package com.jungle.client;

import com.google.gson.reflect.TypeToken;
import com.jungle.bfi.domain.vo.DatasetVo;
import com.jungle.client.channel.HttpClient;
import com.jungle.client.vo.NameValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.input.KeyEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.jungle.client.FxApplication.bundle;

@Slf4j
public class SelectionDialogController implements Initializable {
    @FXML
    private TableView<NameValue> tableView;
    @FXML
    private TextField filterField;
    @FXML
    private TableColumn<NameValue, Boolean> checkColumn;

    public NameValue getSelectedValue() {
        return tableView.getSelectionModel().getSelectedItem();
    }

    public void initialize(java.net.URL location, java.util.ResourceBundle resources) {
        log.info("init SelectionDialogController, location:{}", location);

        tableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        checkColumn.setCellFactory(CheckBoxTableCell.forTableColumn(checkColumn));

        tableView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            log.info("selectedItemProperty, oldValue:{}, newValue:{}", oldValue, newValue);
            if (newValue != null) {
                newValue.setChecked(true);
                tableView.getSelectionModel().select(newValue);
            }
        });
        filterField.requestFocus();
    }

    @FXML
    private void doQuery(ActionEvent event) {
        doQuery();
    }

    @FXML
    private void doKeyQuery(KeyEvent event) {
        log.info("doKeyQuery, event:{}", event);
        if (event.getCode() == javafx.scene.input.KeyCode.ENTER) {
            doQuery();
        }
    }

    private void doQuery() {
        String text = filterField.getText();
        loadData(text);
    }

    private void loadData(String text) {
        Map<String, String> query = new java.util.HashMap<>();
        if (text != null && !text.isEmpty()) {
            query.put("name", text);
        }
        HttpClient.getInstance().post("/dataset/list", query).callback(new TypeToken<List<DatasetVo>>() {
        }, list -> {
            log.info("list: {}", list);
            tableView.getItems().clear();
            if (list != null && !list.isEmpty()) {
                List<NameValue> nameValues = list.stream().map(item -> {
                    NameValue nameValue = new NameValue();
                    nameValue.setName(item.getName());
                    nameValue.setValue(item.getId());
                    return nameValue;
                }).toList();
                tableView.getItems().addAll(nameValues);
            }
        });
    }

    public void doCancel(ActionEvent event) {
        log.info("doCancel, event:{}", event);
        Stage stage = (Stage) tableView.getScene().getWindow();
        // 清除选中行
        tableView.getSelectionModel().clearSelection();
        stage.close();
    }

    public void doOk(ActionEvent event) {
        log.info("doOk, event:{}", event);
        if (tableView.getSelectionModel().getSelectedItem() != null) {
            Stage stage = (Stage) tableView.getScene().getWindow();
            stage.close();
        }
    }

    public static NameValue showSelectionDialog() throws IOException {
        FXMLLoader loader = new FXMLLoader(SelectionDialogController.class.getResource("SelectionDialog.fxml"));
        loader.setResources(bundle);
        Parent root = loader.load();

        SelectionDialogController controller = loader.getController();

        Stage dialogStage = new Stage();
        dialogStage.setTitle(bundle.getString("selection.dialog.title"));
        dialogStage.setScene(new Scene(root));
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        dialogStage.showAndWait();

        return controller.getSelectedValue();
    }
}
